<template>
  <div>
    <el-popover
      :disabled="disabled"
      v-model="showTable"
      placement="bottom-start"
      trigger="click">
      <el-tree v-loading="loading" :data="treeData" :props="props1" node-key="id" :load="loadNode1" :lazy="lazy" :show-checkbox="multiple" @check-change="checkChange" :highlight-current="!multiple" @current-change="currentChange" ref="elTree" style="max-height: 350px;overflow: auto" :default-expanded-keys="expandKeys"></el-tree>
      <el-input :disabled="disabled" v-model="currentValue" placeholder="" slot="reference" clearable readonly @clear="clearInput" class="hover-hide">
        <i v-if="!disabled" slot="suffix" :class="'hover-icon el-input__icon ' + (showTable?'el-icon-arrow-up':'el-icon-arrow-down')"></i>
      </el-input>
    </el-popover>
  </div>
</template>
<script>
  import qs from 'qs'
  export default {
    data() {
      return {
        props1: {
          label: 'categoryName',
          children: 'children',
          isLeaf: 'isLeaf' //判断是否含有子节点的判断
        },
        currentValue:'',
        currentCode:'',
        showTable: false,
        resultData:{},
        treeData:[],
        expandKeys:[],
        loading: false
      };
    },
    props:{
      multiple:{
        type: Boolean,
        default: true
      },
      value: {
        type: String
      },
      disabled:{
        type: Boolean,
        default: false
      },
      code:{
        type: String
      },
      lazy:{
        type: Boolean,
        default: true
      }
    },
    created(){
      this.currentValue = this.value;
      this.currentCode = this.code?this.code.split(','): '';
      if (!this.lazy) {
        this.loading = true;
        this.axios.post(this.lib.config.host.system + '/mainsupplycategory/query', {}).then((res)=>{
          this.loading = false;
          this.treeData = this.transformToTreeFormat(res.data);
          if (this.code && this.code !== '' && !this.multiple) {
            this.expandKeys.push(this.code);
            this.$nextTick(()=>{
              this.$refs.elTree.setCurrentKey(this.code);
              if (this.value === '') {
                let node = this.$refs.elTree.getNode(this.code);
                this.currentValue = node.data.categoryName;
                this.$emit('input', this.currentValue);
              }
            });
          } else if (this.code && this.code !== '' && this.multiple) {
            this.code.split(',').forEach((item)=>{
              this.expandKeys.push(item);
            });
            this.$nextTick(()=>{
              this.$refs.elTree.setCheckedKeys(this.code.split(','));
              if (this.value === '') {
                this.code.split(',').forEach((item, index)=>{
                  let node = this.$refs.elTree.getNode(item);
                  this.currentValue += (index === 0? '': ',') + node.data.categoryName;
                  this.$emit('input', this.currentValue);
                });
              }
            });
          }
        }).catch((e)=>{
          this.loading = false;
        });
      }
    },
    methods: {
      loadNode1(node, resolve) {
        let data;
        if (node.data) {
          data = {
            parentId: node.data.id
          }
        }
        this.axios.post(this.lib.config.host.system + '/mainsupplycategory/getCategorries', qs.stringify(data)).then((response)=>{
          resolve(response.data);
        }).catch(()=>{
          resolve([]);
        });
      },
      checkChange(data, isCheck, children){
        if (isCheck) {
          this.$set(this.resultData, data.id, data);
        } else {
          if (this.resultData[data.id]) {
            this.$delete(this.resultData, data.id);
          }
        }
      },
      currentChange(data, node){
        if (!this.multiple) {
          this.resultData = data;
        }
      },
      clearInput(){
        this.resultData = {};
        if (this.multiple) {
          this.$refs.elTree.setCheckedKeys([]);
        } else {
          this.$refs.elTree.setCurrentKey();
        }
      },
      getResultData(){
        if (this.multiple) {
          return Object.values(this.resultData);
        } else {
          return this.resultData;
        }
      },
      transformToTreeFormat(array){
        let i,l,
          key = 'id',
          parentKey = 'parentId',
          childKey = 'children';

        if (array instanceof Array) {
          let r = [];
          let tmpMap = {};
          for (i=0, l=array.length; i<l; i++) {
            if (array[i]) {
              tmpMap[array[i][key]] = array[i];
            }
          }
          for (i=0, l=array.length; i<l; i++) {
            if (array[i] && tmpMap[array[i][parentKey]] && array[i][key] !== array[i][parentKey]) {
              if (!tmpMap[array[i][parentKey]][childKey])
                tmpMap[array[i][parentKey]][childKey] = [];
              tmpMap[array[i][parentKey]][childKey].push(array[i]);
            } else {
              r.push(array[i]);
            }
          }
          return r;
        } else {
          return [array];
        }
      }
    },
    watch:{
      value(val){
        this.currentValue = val;
      },
      code(val){
        this.currentCode = val?val.split(','):'';
      },
      resultData(val){
        this.currentValue = '';
        this.currentCode = '';
        if (this.multiple) {
          let arr = Object.values(val);
          arr.forEach((item, index)=>{
            this.currentValue += (index === 0? '': ',') + item.categoryName;
            this.currentCode += (index === 0? '': ',') + item.categoryCode;
          });
        } else {
          this.currentValue = this.resultData.categoryName;
          this.currentCode = this.resultData.categoryCode;
        }
        this.$emit('input', this.currentValue);
        this.$emit('update:code', this.currentCode);
      }
    }
  };
</script>
